package com.fast.service;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.fast.dao.SysUserMapper;
import com.fast.domain.SysUser;
import com.fast.web.security.ShiroDbRealm.ShiroUser;
import com.fast.web.security.utils.Digests;
import com.fast.web.utils.Encodes;

@Service
public class UserService {
	private final Logger logger = LoggerFactory.getLogger(getClass());
	public static final String HASH_ALGORITHM = "SHA-1";
	public static final int HASH_INTERATIONS = 1024;
	private static final int SALT_SIZE = 8;

	@Autowired
	private SysUserMapper sysUserMapper;

	public List<SysUser> getAll() {
		return sysUserMapper.selectByExample(null);
	}

	public SysUser findUserByLoginName(String loginName) {
		SysUser sysUser = new SysUser();
		sysUser.setLoginName(loginName);
		return sysUserMapper.selectOne(sysUser);
	}

	/**
	 * 设定安全的密码，生成随机的salt并经过1024次 sha-1 hash
	 */
	private void entryptPassword(SysUser user, String plainPassword) {
		byte[] salt = Digests.generateSalt(SALT_SIZE);
		user.setSalt(Encodes.encodeHex(salt));

		byte[] hashPassword = Digests.sha1(plainPassword.getBytes(), salt,
				HASH_INTERATIONS);
		user.setPassword(Encodes.encodeHex(hashPassword));
	}

	/**
	 * 取出Shiro中的当前用户LoginName.
	 */
	private String getCurrentUserName() {
		ShiroUser user = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
		return user.getName();
	}

	public void save(SysUser user) {
		SysUser sysUser = findUserByLoginName("thinkgem");
		// 设定安全的密码，生成随机的salt并经过1024次 sha-1 hash
		entryptPassword(sysUser, "111111");
		sysUserMapper.updateByPrimaryKey(sysUser);
		logger.info("The User password is updated to {} and the salt is {} ",
				sysUser.getPassword(), sysUser.getSalt());
	}
}
